package com.gitee.feizns.explore.data_structure.tree.bs.easy;

/**
 * 606. 根据二叉树创建字符串
 * @author feizns
 * @since 2020/1/4
 */
public class Tree2str {

    public static void main(String[] args) {
        System.out.println(tree2str(create()));
    }

    private static TreeNode create() {
        TreeNode ret = new TreeNode(1);
        ret.left = new TreeNode(2);
        ret.left.right = new TreeNode(4);
        ret.right = new TreeNode(3);
        return ret;
    }

    public static String tree2str(TreeNode t) {
        return preOrder(t, new StringBuilder()).toString();
    }

    private static StringBuilder preOrder(TreeNode t, StringBuilder str) {
        if ( t != null ) {
            str.append(t.val);
            if ( t.left != null || t.right != null ) {
                str.append("(");
                preOrder(t.left, str);
                str.append(")");
                if ( t.right != null ) {
                    str.append("(");
                    preOrder(t.right, str);
                    str.append(")");
                }
            }
        }
        return str;
    }

}
